package com.wiringweb.resolution;

import com.wiringweb.servlet.WiringRequestProcessor;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sad
 */
public class RedirectResolution implements Resolution {

    private String location;

    public RedirectResolution(String location) {
        this.location = location;
    }

    private void makeTemporaryRedirect(HttpServletResponse response, String path) throws IOException {
        response.sendRedirect(path);
    }

    private void makePermanentRedirect(HttpServletResponse response, String path) throws IOException {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location", path);
    }

    @Override
    public void process(HttpServletRequest request, HttpServletResponse response, WiringRequestProcessor requestProcessor, ServletConfig servletConfig) throws IOException {
        String urlLowerCase = location.toLowerCase();
        if (urlLowerCase.startsWith("http://")
                || urlLowerCase.startsWith("https://")
                || urlLowerCase.startsWith("ftp://")
                || urlLowerCase.startsWith("rtmp://")
                || urlLowerCase.startsWith("ftps://")
                || urlLowerCase.startsWith("sftp://")) {
            makePermanentRedirect(response, location);
        } else {
            String url;
            if (location.startsWith("/")) {
                url = request.getContextPath() + location;
            } else {
                url = location;
            }
            makeTemporaryRedirect(response, url);
        }
    }
}
